package com.cskaoyan.config;

import com.cskaoyan.bean.domain.FootPrint;
import com.cskaoyan.bean.domain.FootPrintExample;
import com.cskaoyan.bean.domain.User;
import com.cskaoyan.mapper.FootPrintMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;


/**
 * @User: Yr
 * @Date: 2021/12/5
 * @Description: 用于实现wx商城---浏览足迹模块
 */

@Aspect
@Component
public class FootprintAspectJ {
    @Autowired
    FootPrintMapper footPrintMapper;

    @Around("execution(* com..WxUserController.detail(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = joinPoint.proceed();
        //访问商品详情页后 新增/更新足迹表
        FootPrint footPrint = new FootPrint();
        //获取当前userId和goodsId
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            User user = (User) subject.getPrincipal();
            footPrint.setUserId(user.getId());
            Object[] args = joinPoint.getArgs();
            Integer goodsId = (Integer) args[0];
            footPrint.setGoodsId(goodsId);
            //根据goodsId和userId判断是否访问过该删商品
            FootPrintExample example = new FootPrintExample();
            example.createCriteria().andGoodsIdEqualTo(goodsId).andUserIdEqualTo(user.getId());
            List<FootPrint> footPrintList = footPrintMapper.selectByExample(example);
            if (footPrintList.size() > 0) {
                //访问过则更新足迹时间即可
                footPrint.setUpdateTime(new Date());
                footPrintMapper.updateByExampleSelective(footPrint, example);
            } else {
                //未访问过则新增足迹
                footPrint.setAddTime(new Date());
                footPrint.setUpdateTime(new Date());
                footPrintMapper.insertSelective(footPrint);
            }
            return proceed;
        }else {
            return proceed;
        }
    }
}
